<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Summernote</title>
  <link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.css" rel="stylesheet">
 	<!-- jquery高版本 -->
	<script src="${_root}/resources/js/jquery-3.2.1.js"></script>
  <script type="application/javascript">
  	$jq3=jQuery.noConflict();
  	console.log("$jq3的version:"+$jq3().jquery);
  </script>
  <link href="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.8/summernote.css" rel="stylesheet">

	    <link rel="stylesheet" type="text/css" href="${_root}/resources/t2/stylesheets/theme.css">
    <link rel="stylesheet" type="text/css" href="${_root}/resources/t2/stylesheets/premium.css">
	<link rel="stylesheet" type="text/css" href="${_root}/resources/css/jquery.tmailsilder.v2.css" />
	
	<!--文件上传插件-->
	<link rel="stylesheet" href="${_root}/resources/css/fileinput.min.css" />
	<link href="${_root}/resources/css/formValidation.min.css" />
		<!--右键和消息弹框提醒-->
	<link rel="stylesheet" href="${_root}/resources/css/toastr.css">
	<link rel="stylesheet" href="${_root}/resources/css/highlight-8.6.default.min.css">
</head>
<body class="theme-blue">
	<script type="text/javascript">
		$(function(){
			var msg = '${msg}';
			if(msg){
				toastr.info(msg);
			}
		})
	</script>
	<%@include file="/WEB-INF/jsp/common/top.jsp" %>
	<div class="sidebar-nav">
			<ul class="nav nav-pills nav-stacked">
			  <li role="presentation"  ><a href="${_root}/jsp/person">个人信息</a></li>
			  <li role="presentation" class="active"><a href="${_root}/article/uparticle">上传文章</a></li>
			  <li role="presentation"><a href="${_root}/jsp/collection">收藏的文章</a></li>
			  <li role="presentation"><a href="${_root}/jsp/articlemanager">文章管理</a></li>
			</ul>
	</div>
	<div class="content container-fluid" style="margin-top:50px">
		 <form action="/cms/user/uparticle" enctype="multipart/form-data" method="post" id="myform">
		<div class="row">
			<div class="col-lg-10">
				<div class="form-group">
					<button type="submit" id="submit" class="btn btn-lg btn-primary">发布文章</button>
				</div>
			</div>
		</div>
		<div class="row">
			<div class="col-lg-10">
			<div class="panel panel-default">
	   <div class="panel-heading">
	      <h3 class="panel-title">
	        	文章上传
	      </h3>
	   </div>
	   <div class="panel-body">
	     
			<div class="form-group">
				<label>文章标题：</label>
				<input type="text" class="form-control"  name="title" placeholder="文章标题">
			</div>
			<div class="form-group">
				<label>文章封面：</label>
				<input id="file-0a" class="file" type="file" name="file" placeholder="请选择封面"  data-min-file-count="1">
			</div>
		<div class="form-group">
    <label for="articleType">文章分类：</label>
        <select name="typeID" data-placeholder="Your Favorite Football Team" id="articleType" class="form-control chzn-select" tabindex="5">
            <c:forEach items="${result.data.articleTypes}" var="item1">
				<c:if test="${item1.pid==1}">
					<optgroup label="${item1.name}">
					<c:forEach items="${result.data.articleTypes}" var="item2">
						<c:if test="${item1.id==item2.pid}">
							<option value="${item2.id}">${item2.name}</option>
						</c:if>
					</c:forEach>
				</c:if>
			</c:forEach>
           </select>

			</div>
			<div class="form-group">
				<label for="exampleInputPassword1">文章概述:</label>
				<textarea class="form-control" rows="3" name="introduction"></textarea>
			</div>
			<div class="form-group">
				<label for="exampleInputPassword1">请输入内容:</label>
				<div class="form-control" id="summernote">
					请填写你的文章内容。
				</div>
			</div>
			<!--用来存放summernote编辑器的的内容-->
			<input type="hidden" name="content" value="" />
		</form>
	   </div>
	</div>
			  <div id="content">
			  	<div class="row">
			  		<div class="col-lg-12">
			  			
			  		</div>
	  	</div>
	  	
	  </div>
			</div>
		</div>
		 
	</div>
	<!-- 底部资源 -->
	  <script src="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.8/summernote.js"></script>
	<%@include file="/WEB-INF/jsp/common/buttom_resources.jsp"%>
	
		<!--右键功能-->
		<script type="text/javascript" src="${_root}/resources/js/BootstrapMenu.min.js" ></script>
		<script type="text/javascript" src="${_root}/resources/js/toastr.js" ></script>
		<script type="text/javascript" src="${_root}/resources/js/highlight-8.6.default.min.js" ></script>
		<script type="text/javascript" src="${_root}/resources/js/scale.fix.js" ></script>
<script type="text/javascript" src="${_root}/resources/js/jquery.tmailsilder.v2.js" ></script>
  <script>
	//初始化富文本编辑器,初始化地址为#summernote
	$jq3(document).ready(function() {
			var EmptyButton = function(context) {
				var ui = $jq3.summernote.ui;
				var button = ui.button({
					contents: '<i class="note-icon-trash"/>',
					tooltip: '清除全部内容',
					click: function() {
						context.invoke('editor.empty');
					}
				});
				return button.render();
			};
			var CleanWordButton = function(context) {
				var ui = $jq3.summernote.ui;
				var button = ui.button({
					contents: '<i class="note-icon-square"/>',
					tooltip: '清除Word格式',
					click: function() {
						//  清除img的wrap元素  
						var str = context.invoke('code');
						console.log("before:"+str);
						str = CleanPastedHTML(str); //  class="hidden"  
						console.log(str);
//						$('.container').append('<div id="tmp">' + str + '</div>');
//						$('#tmp table img').unwrap();
//						str = $('#tmp').html();
//						str = CleanPastedHTML(str); //  class="hidden"  
//						$('#tmp').remove();
						context.invoke('code', str);
					}
				});
				return button.render();
			};//初始化summernote
      $jq3('#summernote').summernote({
      	 lang: 'zh-CN',  
		        height: 300,  
		        minHeight: 200, // set minimum height of editor  
		        // maxHeight: null, // set maximum height of editor  
		        focus: true, // set focus to editable area after initializing su   
		        dialogsInBody: true,  
		        dialogsFade: true, // Add fade effect on dialogs,  
		        disableDragAndDrop: true,  
		        shortcuts: true,  
		        placeholder: '在这里添加内容',
		        toolbar: [
		        ['style', ['style']],
		        ['font', ['bold', 'underline', 'clear','word','empty']],
		        ['fontname', ['fontname']],
		        ['color', ['color']],
		        ['para', ['ul', 'ol', 'paragraph']],
		        ['table', ['table']],
		        ['insert', ['link', 'picture', 'hr']],
		        ['view', ['fullscreen', 'codeview', 'help']]
    		],
    		styleTags: ['p', 'blockquote', 'pre', 'h2', 'h3', 'h4', 'h5', 'h6'],
      	callbacks:{
      		//定义图片上传时的回调函数
      		onImageUpload:imgUploadHandler
      	},
      	buttons: {empty: EmptyButton, word: CleanWordButton}
      });
      /**
       * 
       * @param {Object} files 当富文本编辑器有图片插入时的FileList
       */function imgUploadHandler(files) {
				const upUrl = "/cms/user/uploadImage";
				$fileList = $jq3(files); //封装为jquery对象
				//循环上传每一张图片到服务器
				$fileList.each(function(){
						var formData = new FormData();
						formData.append("file", this); //通过FormData对象来上传二进制文件
						$jq3.ajax(upUrl, {
							data: formData,
							type: 'POST',
							cache: false,
							contentType: false,
							processData: false,
							dataType: 'json',
							success: function(result) {
								const serverIP = "${_ip}";
								const url = 'http://' + serverIP + result.data.url; //要使用完整的url
								console.log("服务器端传回的url为:" + url);
								//然后append进富文本编辑器
								$jq3('#summernote').summernote("insertImage", url, function($image) {
			
								});
			
							}
						});
				});
			}
	
       /*
		   	 对复制粘贴的字符串进行处理
		   	 * */
		   	function CleanPastedHTML(input) {  
				      // 1. remove line breaks / Mso classes  
				      var stringStripper = /(\n|\r| class=(")?Mso[a-zA-Z]+(")?)/g;  
				      var output = input.replace(stringStripper, ' ');  
				      // 2. strip Word generated HTML comments  
				      var commentSripper = new RegExp('<!--(.*?)-->','g');  
				      var output = output.replace(commentSripper, '');  
				      var tagStripper = new RegExp('<(/)*(meta|link|span|\\?xml:|st1:|o:|font)(.*?)>','gi');  
				      // 3. remove tags leave content if any  
				      output = output.replace(tagStripper, '');  
				      // 4. Remove everything in between and including tags '<style(.)style(.)>'  
				      var badTags = ['style', 'script','applet','embed','noframes','noscript'];  
				      
				      for (var i=0; i< badTags.length; i++) {  
				        tagStripper = new RegExp('<'+badTags[i]+'.*?'+badTags[i]+'(.*?)>', 'gi');  
				        output = output.replace(tagStripper, '');  
				      }  
				      // 5. remove attributes ' style="..."'  
				      var badAttributes = ['style', 'start'];  
				      for (var i=0; i< badAttributes.length; i++) {  
				        var attributeStripper = new RegExp(' ' + badAttributes[i] + '="(.*?)"','gi');  
				        output = output.replace(attributeStripper, '');  
				      }  
				      return output;  
		    }
		   
  });
   	(function(){
   		$jq3('#myform').on('submit',function(event){
   			var content=$jq3('#summernote').summernote('code');
   			var $ele=$jq3('input[name="content"]',$jq3('#myform'));
   			$ele.prop('value',content);
   			$jq3('#myform').formValidation('validate');//验证表单
   			return false;
   		})
   	})();
   	$jq3('#myform').formValidation({
   				message:'不是有效的值',
					icon:{
						valid: 'glyphicon glyphicon-ok',
			            invalid: 'glyphicon glyphicon-remove',
			            validating: 'glyphicon glyphicon-refresh'
					},
					fields:{
						title:{
								message:'文章标题不能为空',
								validators:{
									notEmpty:{
										message:'文章标题不能为空'
									},
									stringLength:{
										min:1,
										max:50,
										message:'标题长度必须在1-50个字符之间'
									}
								}
						},
						type:{
							validators:{
									notEmpty:{
										message:'文章类型不能为空'
									}
								}
						},
						introduction:{
								validators:{
									notEmpty:{
										message:'文章描述不能为空'
									}
								}
						}
					}
   		
   	}).on('success.form.fv',function(e){
   		//表单验证成功，手动提交表单
   	 	e.preventDefault();//阻止事件冒泡
   	 	$jq3('#myform').submit();
   	});
  </script>
</body>
</html>